<template>
  <el-select
      v-model="newv"
      :class="className"
      :placeholder="placeholder || place"
      :value-key="valueKey"
      :clearable="isClearable"
      :disabled="isDisabled"
      @change="$emit('change', $event)"
  >
    <el-option
        v-for="(e, i) in options ? options : items"
        :key="i"
        :label="e.label"
        :value="e.value"
    ></el-option>
  </el-select>
</template>

<script setup>
import {ref, computed, watch} from 'vue';

const props = defineProps({
  modelValue: [Object, String, Number, Boolean],
  className: {
    type: String,
    default: "wda-select",
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  type: {
    type: Number,
    default: 0,
  },
  options: {
    type: Array,
    default: null,
  },
  valueKey: {
    type: String,
    default: "value",
  },
  initial: {
    type: Boolean,
    default: false,
  },
  isClearable: {
    type: Boolean,
    default: false,
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
  args: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

// 响应式数据
const items = ref([]);
const place = ref("请选择");

const newv = computed({
  get() {
    let reset = false;
    let def = null;
    if (items.value && items.value.length) {
      if (props.modelValue != null) {
        if (typeof props.modelValue == "object") {
          reset = !items.value.some((e) => {
            if (e.value[props.valueKey] === props.modelValue[props.valueKey]) {
              if (e.value !== props.modelValue) {
                def = e.value;
              }
              return true;
            }
          });
          if (def != null) {
            reset = true;
          }
        } else {
          reset = !items.value.some((e) => e.value === props.modelValue);
        }
        if (reset && props.initial && def == null) {
          def = items.value[0].value;
        }
      } else if (props.initial) {
        reset = true;
        def = items.value[0].value;
      }
    }
    if (reset) {
      emit('update:modelValue', def);
    }
    return props.modelValue === true ? "" : props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  },
});

// 监听 options 属性的变化
watch(() => props.options, (newOptions) => {
  if (props.type === 0) {
    items.value = newOptions;
  }
}, {immediate: true});
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
